<template>
    <div class="container">
        <div class="toast-top">{{imgFrom ? '当前头像来自【' + imgFrom + '】' : ''}}</div>
        <div class="canvas-box">
            <canvas id="myCanvas" width="243" height="243"></canvas>
        </div>
        <div>
            <div class="toast-middle"><span class="triangle">▲ ▲</span>点击图片可调整位置大小呦<span class="view-demo">查看示例</span><span class="triangle">▲ ▲</span></div>
            <div class="swiper-style">
                <swiper :options="swiperOption" ref="mySwiper" class="swiper-contanier">
                    <swiper-slide v-for="(pageList, i) in wangLibrary" :key="'swiper-' + i">
                        <div class="slider-item">
                            <div @click="clickImageItem(item)" class="item-image" v-for="(item, it) in pageList" :key="'image'+it">
                                <img :src="item.url" alt="">
                            </div>
                        </div>
                    </swiper-slide>
                </swiper>
                <div class="swiper-pagination"  slot="pagination"></div>
                <div class="big-btn" @click="goToEdit">选好了，去带围巾</div>
            </div>
        </div>
        <div v-transfer-dom>
            <x-dialog v-model="showHideOnBlur" class="dialog-layout" hide-on-blur>
                <div class="dialog-container">
                    <div class="dialog-matrial">
                        <MaterialItem :data="activeMatrial"></MaterialItem>
                    </div>
                    <div class="dialog-btn-group">
                        <button class="button-red" @click="buyItem(activeMatrial)">{{activeMatrial.price}}毛解锁这个素材</button>
                        <button class="button-red" @click="buyVIP">1元解锁全部素材</button>
                        <button @click="showHideOnBlur=false">我穷，我用免费的。</button>
                    </div>
                </div>
                <div @click="showHideOnBlur=false">
                    <span class="vux-close"></span>
                </div>
            </x-dialog>
        </div>
        <div is="copyright"></div>
        <div v-if="showAd" class="place-space"></div>
        <div v-if="showAd" class="ad"></div>
    </div>
</template>

<script>
import { swiper, swiperSlide } from 'vue-awesome-swiper';
import 'swiper/dist/css/swiper.css';
import store from 'store';

import fabric from 'fabric';
import wx from 'wx';
import wallet from '@caomei/wallet';

import { Tab, TabItem, XDialog, TransferDomDirective as TransferDom } from 'vux';
import MaterialItem from '../components/MaterialItem';

import copyright from '../components/copyright';
import api from '../api/index';
import { clearTimeout } from 'timers';

export default {
    data() {
        return {
            imgFrom: '',
            showAd: false,
            library: [],
            activeTab: 0,
            userInfo: {},
            canvasConfig: {
                width: 243,
                height: 243
            },
            activeMatrial: {},
            showHideOnBlur: false,
            canvas: null,
            swiperOption: {
                delay: 3000,
                pagination: {
                    el: '.swiper-pagination'
                },
                paginationClickable: true
            }
        };
    },
    directives: {
        TransferDom
    },
    computed: {
        swiper() {
            return this.$refs.mySwiper.swiper;
        },
        wangLibrary() {
            if (!this.library) return [];
            let newArr = this.library.filter(val => val.itemKindId === '65938575f4ad4cf69d40cc19edcdc695');
            if (!newArr.length) return [];
            let library = newArr[0].wxItemVOList;
            for (let i = 0; i < 8; i += 1) {
                library = library.concat(newArr[0].wxItemVOList);
            }
            let res = [];
            for (let i = 0; i < Math.ceil(library.length / 8); i += 1) {
                res[i] = library.slice(i * 8, (i + 1) * 8);
            }
            return res;
        }
    },
    methods: {
        buyVIP() {
            this.$buy('5bfaa33d68194d39b9f81aea88b6808b', 1, 1);
        },
        buyItem(item) {
            this.$buy(item.itemId, 1, 0);
        },
        addImageToCanvas(path) {
            this.canvas.clear();
            /* eslint-disable */
            new fabric.Image.fromURL(path, (img) => {
                if (img.width > img.height) {
                    let x = this.canvasConfig.height / img.height;
                    img.minScaleLimit = x;
                    img.scaleX = x;
                    img.scaleY = x;
                } else {
                    let x = this.canvasConfig.width / img.width;
                    img.minScaleLimit = x;
                    img.scaleX = x;
                    img.scaleY = x;
                }
                img.lockRotation = true;
                this.canvas.add(img);
            }, {
                hasControls: false,
                centeredScaling: false,
                crossOrigin: 'anonymous'
            });
            /* eslint-enable */
        },
        clickImageItem(item) {
            if (item.price > 10) {
                this.activeMatrial = item;
                this.showHideOnBlur = true;
                return;
            }
            item.url && this.addImageToCanvas(item.url);
        },
        goToEdit() {
            store.set('EDIT_IMAGE', this.canvas.toDataURL());
            this.$router.push({name: 'edit'});
        },
        testPay() {
            if (wallet.isSupportedPayType('wxpay')) {
                wallet.wxpay.payIt({ tradeNO: 'mock' })
                .then(res => { alert('支付成功'); })
                .catch(res => {
                    if (res.resultCode === wallet.wxpay.CANCEL) {
                        alert('取消了支付');
                    } else {
                        alert('支付失败');
                    }
                });
            } else {
                console.error(wallet.toString() + '不支持wxpay!'); // 当前平台为web, 环境客户端为alipay, 支持的支付类型为alipay。不支持wxpay!
            // TODO 甩锅给服务端
            }
        }
    },
    created() {
        console.log(this.config);
        let url = window.location.href;
        api.getUserInfo().then((res) => {
            this.userInfo = res;
        });
        api.getJsTicket(url, this.config.appId).then((res) => {
            wx.config({
                debug: true,
                appId: res.appId,
                nonceStr: res.nonceStr,
                timestamp: res.timestamp,
                signature: res.signature,
                jsApiList: ['chooseImage', 'getLocalImgData']
            });
        });
        api.getItemsList().then((res) => {
            this.library = res;
        });
    },
    mounted() {
        // this.initSwiper();
        /* eslint-disable */
        wx.checkJsApi({
            jsApiList: ['chooseImage'],
            success: (res) => {
                console.log('sdf', res);
            }
        });
        const canvas = new fabric.Canvas('myCanvas');
        canvas.selection = false;
        this.canvas = canvas;
        canvas.on({
            // 'touch:drag': function(val) {
            //     console.log(val);
            //     val.self.pause();
            // },
            'object:moving': function(val) {
                let target = val.target;
                if (target.left > 0) target.left = 0;
                if (target.top > 0) target.top = 0;
                let wl = target.width * target.scaleX;
                let hl = target.height * target.scaleY;
                target.right = target.left + wl;
                target.bottom = target.top + hl;
                if (target.right < 243) target.left = 243 - wl;
                if (target.bottom < 243) target.top = 243 - hl;
            },
            'object:scaling': function(val) {
                let target = val.target;
                let wl = target.width * target.scaleX;
                let hl = target.height * target.scaleY;
                target.top = hl / 2;
                target.left = wl / 2;
                /*
                target.translateToOriginPoint({}, 'nmcenter', 'center');
                if (target.left >  - (wl / 2)) {
                    target.left = - (wl / 2);
                    target.originX = 'left';
                    target.translateToOriginPoint({}, 'left', 'center');
                }
                if (target.top >  - (hl / 2)) {
                    target.top = - (hl / 2);
                    target.originY = 'top';
                    target.translateToOriginPoint({}, 'center', 'left');
                }

                target.right = target.left + wl;
                target.bottom = target.top + hl;
                if (target.right < 243) {
                    target.left = 243 - wl;
                    target.originX = 'right';
                    target.translateToOriginPoint({}, 'right', 'center');
                }
                if (target.bottom < 243) {
                    target.top = 243 - hl;
                    target.originY = 'bottom';
                    target.translateToOriginPoint({}, 'center', 'right');
                }
                */
            }
            // 'touch:orientation': function() {
            // },
            // 'touch:shake': function() {
            // },
            // 'touch:longpress': function() {
            // }
        });
        let editImage = store.get('EDIT_IMAGE');
        if (editImage) {
            this.addImageToCanvas(editImage);
        }
    },
    components: {
        copyright,
        Tab, TabItem,
        swiper,
        swiperSlide, XDialog,
        MaterialItem
    }
};
</script>

<style lang="less">
@primaryColor: #D3502B;
// @primaryColor: #FFFFFF;
.container {
    background: #F6F5F1 url('../assets/images/bg.png') no-repeat;
    background-size: contain;
    height: 100%;
    width: 100%;
    .toast-top {
        height: 16px;
        width: 100%;
        text-align: center;
        font-size: 12px * 2;
        padding: 30px * 2 0 6px * 2;
        color: #B34424;
    }
    .toast-middle {
        font-size: 12px * 2;
        color: #8B8B8B;
        padding: 5px * 2 15px * 2;
        text-align: center;
        font-weight: lighter;
        line-height: 1;
        .triangle {
            transform: scale(0.5);
            display: inline-block;
        }
    }
    .swiper-style {
        position: relative;
        .swiper-contanier {
            height: auto;
        }
        .slider-item {
            position: relative;
            line-height: 1;
            display: flex;
            flex-wrap: wrap;
            width: 708px;
            margin: 0 auto;
            justify-content: flex-start;
            .item-image {
                width: 177px;
                height: 159px;
                margin-bottom: 11px;
                overflow: hidden;
                display: flex;
                justify-content: center;
                img {
                    width: 159px;
                    height: 159px;
                    border-radius: 12px;
                    border: 2px solid @primaryColor;
                    box-sizing: border-box;
                    // height: 80px;
                }
            }
        }
        .big-btn {
            width: 690px;
            margin: 0 auto;
            height: 44px * 2;
            background-color: @primaryColor;
            border: 1px solid #B63C19;
            border-radius: 5px * 2;
            color: #FFFFFF;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 36px;
        }
    }
    .swiper-pagination-bullet{
        background: #D8D8D8;
        opacity: 0.2;
        width: 21px;
        height: 21px;
        margin: 0 10px;
    }
    .swiper-pagination-bullet-active {
        background: @primaryColor !important;
        opacity: 1;
    }
    .swiper-pagination-bullets {
        bottom: 20px !important;
        position: relative;
    }
    .canvas-box {
        margin: 0 auto;
        width: 243px * 2;
        height: 243px * 2;
        #myCanvas {
            background: #FFFFFF url('../assets/images/canvas-bg-a.png') no-repeat;
            background-size: contain;
            border: 1px dashed @primaryColor;
            box-sizing: border-box;
            width: 243px * 2 !important;
            height: 243px * 2 !important;
        }
    }
    .canvas-container {
        margin: 0 auto;
    }
    
    .place-space {
        height: 65px * 2;
    }
    .ad {
        height: 65px * 2;
        width: 100%;
        background-color: #8B8B8B;
        position: fixed;
        bottom: 0;
    }
}
</style>
